<template>
  <div>
    <!-- 搜索页面头部 -->
    <div class="search-header">
      <!-- 后退按钮 -->
      <van-icon
        name="arrow-left"
        color="white"
        size="0.48rem"
        class="goback"
        @click="$router.back()"
      />
      <!-- 搜索组件 -->
      <van-search
        v-fofo
        placeholder="请输入搜索关键词"
        background="#007BFF"
        shape="round"
        v-model="kw"
        @input="inputFn"
        @search="searchFn"
      />
    </div>
    <!-- 搜索联想列表 -->
    <div class="sugg-list" v-if="suggestionList.length > 0">
      <!-- v-html解析标签 -->
      <div
        class="sugg-item"
        v-for="(item, index) in suggestionList"
        :key="index"
        v-html="lightFn(item, kw)"
        @click="clickSuggestFn(item)"
      ></div>
    </div>
    <!-- 搜索历史 -->
    <div class="search-history" v-else>
      <!-- 标题 -->
      <van-cell title="搜索历史">
        <!-- 使用 right-icon 插槽来自定义右侧图标 -->
        <template #right-icon>
          <van-icon name="delete" class="search-icon" @click="history=[]"/>
        </template>
      </van-cell>

      <!-- 历史列表 -->
      <div class="history-list">
        <span class="history-item"
        v-for="(str, index) in history"
        :key="index"
        @click="clickHistoryFn(str)"
        >
        {{ str }}</span>
      </div>
    </div>
  </div>
</template>

<script>
import { getSuggestionAPI } from '@/api'
import { lightFn } from '@/utils/str'
export default {
  name: 'HM-Search',
  data () {
    return {
      kw: '', // 搜索关键字
      timer: null,
      suggestionList: [], // 请求联想关键词
      history: JSON.parse(localStorage.getItem('his')) || [] // 搜索历史
    }
  },
  watch: {
    history () {
      // 存到本地就不会 路由跳转不会销毁之前的组件
      localStorage.setItem('his', JSON.stringify(this.history))
    }
  },
  methods: {
    // 导入的方法只能放在methods中 解析template的模板它是函数不是变量
    lightFn: lightFn,
    // 输入框防抖操作 确定绑定事件（对输入框input事件动作做防抖） 创建定时器包裹逻辑代码 每次触发要清空上一个定时器
    inputFn () {
      clearTimeout(this.timer)
      this.timer = setTimeout(async () => {
        if (this.kw.trim().length === 0) {
          this.suggestionList = [] // 防止空内容触发下面逻辑
        } else {
          const res = await getSuggestionAPI({
            keywords: this.kw
          })
          // console.log(res)
          if (res.data.data.options[0] === null) {
            this.suggestionList = []
          } else {
            this.suggestionList = res.data.data.options
          }
        }
        // console.log(this.kw)
      }, 500)
    },
    // 点击回车 真机上是点击搜索
    searchFn () {
      this.history.push(this.kw)
      // 去重 set
      // const set = new Set([1, 2, 3, 1])
      // Array.from(set)
      this.history = Array.from(new Set(this.history))
      setTimeout(() => {
        this.$router.push(`/search/${this.kw}`)
      }, 100)
    },
    // 点击搜索联想列表
    clickSuggestFn (str) {
      this.history.push(str)
      this.history = Array.from(new Set(this.history))
      setTimeout(() => {
        this.$router.push(`/search/${str}`)
      })
    },
    // 点击历史记录
    clickHistoryFn (str) {
      setTimeout(() => {
        this.$router.push(`/search/${str}`)
      })
    }
  }
}
</script>

<style scoped lang="less">
.search-header {
  height: 46px;
  display: flex;
  align-items: center;
  background-color: #007bff;
  overflow: hidden;
  /*后退按钮*/
  .goback {
    padding-left: 14px;
  }
  /*搜索组件*/
  .van-search {
    flex: 1;
  }
}
/*搜索建议列表样式 */
.sugg-list {
  .sugg-item {
    padding: 0 15px;
    border-bottom: 1px solid #f8f8f8;
    font-size: 14px;
    line-height: 50px;
    // 实现省略号的三行代码
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
}
/**搜索历史 */
.search-icon {
  font-size: 16px;
  line-height: inherit;
}

.history-list {
  padding: 0 10px;
  .history-item {
    display: inline-block;
    font-size: 12px;
    padding: 8px 14px;
    background-color: #efefef;
    margin: 10px 8px 0px 8px;
    border-radius: 10px;
  }
}
</style>
